package kr.hkit.powerjava.chapter17.submit;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.BorderLayout;

public class Swing2 extends JPanel implements ItemListener {
	private JPanel panelChk1;
	private JCheckBox[] chkBtns;
	private JLabel[] lbls;
	private ImageIcon[] icons;
	private JPanel panelChk2;
	
	public Swing2() {
		initialize();
	}
	
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		panelChk1 = new JPanel();
		add(panelChk1, BorderLayout.WEST);
		panelChk1.setLayout(new GridLayout(0, 1, 0, 0));

		Border b= BorderFactory.createTitledBorder("선택"); //경계선
		panelChk1.setBorder(b);
		
		chkBtns = new JCheckBox[3];
		
		String[] strs = { "dog1", "dog2", "dog3" };
		lbls = new JLabel[3];
		icons = new ImageIcon[3];

		for (int i = 0; i < 3; i++) {
			chkBtns[i] = new JCheckBox(strs[i]);
			chkBtns[i].addItemListener(this);
			lbls[i] = new JLabel(strs[i] + ".jpg");
			icons[i] = new ImageIcon(strs[i] + ".jpg");
		}
		
		for (int i = 0; i < 3; i++) {
			panelChk1.add(chkBtns[i]);
		}
		
		panelChk2 = new JPanel();
		add(panelChk2, BorderLayout.CENTER);
		panelChk2.setLayout(new GridLayout(1, 3, 0, 0));
		
		panelChk2.add(lbls[0]);
		panelChk2.add(lbls[1]);
		panelChk2.add(lbls[2]);
		
	}
	
	@Override
	public void itemStateChanged(ItemEvent e) {
		Object source = e.getItemSelectable();
		for (int i = 0; i < 3; i++) {

			if (source == chkBtns[i]) {
				lbls[i].setIcon(icons[i]);

				if (e.getStateChange() == ItemEvent.DESELECTED) {
					lbls[i].setIcon(null);
				} else {
					lbls[i].setIcon(icons[i]);
				}
			}
		}
	}

}
